import React from 'react';
import {Button, Input, Modal,Spin} from 'antd';
import {
    WeaTop,
    WeaLeftRightLayout,
    WeaCollect,
    WeaDialog,
    WeaTab,
    WeaRightMenu,
    WeaTransfer,
    WeaTools,
    WeaLocaleProvider
} from 'ecCom';
import IntegrationForm from './IntegrationForm';
import {MainDataList} from './MainDatalist';
import TopColumn from './MainTopColumn';
import {Initialization} from './Initialization';
import {inject, observer} from 'mobx-react';
import {toJS} from "mobx";
import {CustomInterfaceSetting} from './CustomInterfaceSetting';
import  * as Public from '../public/sendMsg';
import * as Static from '../public/staticEnmu'
import * as conLockApi from '../apis/contractLockSend';
import QYS_Right from './QYS_Right';


const getLabel = WeaLocaleProvider.getLabel;


@inject("myParame", "myDelete", "myTopcol", "myForm", "myStore", "myCreateForm", "myCusIntSet","myCreateForm")//这个
@observer
class Mainpage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // loading: true,
            title: getLabel(383058, "契约锁设置"),
            islayout: false,
            isRight: true,
        }
        const {myParame} = this.props;
        const {initTopTab} = myParame;
        initTopTab();
    }

    /**
     * 取消显示弹出框
     */
    fncanceldialog = () => {
        let {myParame, myCreateForm} = this.props;
        myParame.setVisibleDialog();
        myCreateForm.clearstore();
    }

    /**
     * 弹出删除框
     */
    fndelete = () => {
        const {myStore} = this.props;
        const {tableStore} = myStore;
        if (!(tableStore.selectedRowKeys.length > 0)) {
            Modal.warning({
                title: getLabel(15172, "系统提示"),
                content: getLabel(30951, "请选择需要删除的数据!"),
            });
        } else {
            let params_d = "";
            tableStore.selectedRowKeys.map(((v) => {
                params_d += v + ","
            }));
            this.fnGoDelete(params_d);
        }
    }

    /**
     * 删除
     * @param ids 需要删除的id数组
     */
    fnGoDelete = (ids) => {
        const {myParame, myCreateForm} = this.props;
        const fn = () => {
            this.setState({data: new Date()})
        };

        const {selectedKey, toptab} = myParame;
        let url = "";
        if(toptab[selectedKey] && toptab[selectedKey].deleteurl) {
            url =  toptab[selectedKey].deleteurl;
        }
        //删除提示
        Modal.confirm({
            title: getLabel(131329, "确认信息"),
            content: getLabel(15097, "确定要删除吗？"),
            onOk() {
                conLockApi.currencyRequestPOST(url, {ids: ids}).then(result => {
                    if (result.status == 1) {
                        Modal.success({
                            title: getLabel(15172, "系统提示"),
                            content:  getLabel(83472, "删除成功!") ,
                            onOk() {
                                fn();
                            },
                        });
                    } else {
                        Modal.error({
                            title: getLabel(15172, "系统提示"),
                            content: result.result ? getLabel(83472, "删除成功!") : getLabel(83473, "删除失败!"),
                        });
                    }
                });
            },
            onCancel() {
            },
        });
    }

    /**
     * 编辑数据
     * @param id
     */
    fnEditForm = (id) => {
        this.fnCreateParam("getEditForm", id);
    }

    /**
     *改变状态参数 新建--getCreateForm ，编辑（编辑id)
     * @param type
     */
    fnCreateParam = (type = null, id = null) => {
        let {myParame, myCreateForm} = this.props;
        let parame = {formtype: type, id: id};
        myCreateForm.setFormDatas(myParame.getCreateUrl(), parame);
        myParame.setVisibleDialog();
    }

    /**
     * 显示定制列
     */
    fnColSetVisible = () => {
        const {myStore} = this.props;
        const {tableStore} = myStore;
        tableStore.setColSetVisible(true);
        tableStore.tableColSet(true);
    }

    /**
     * 搜索方法
     */
    fnSearch = () => {
        let {myParame, myForm} = this.props;
        let {showSearchAd, selectedKey} = myParame;
        const {form} = myForm;
        //这里需要判断是否展开了高级搜索
        let parame = {};
        parame = form.getFormParams();
        myParame.setShowSearcheAd(false);
        //TODO 这里是普通搜索时需要使用到的地方
        // if (showSearchAd) {//展开则搜索标识和名称，同时关闭高级搜索
        //     parame ={sysid:sysid, name:name};
        //     myParame.setShowSearcheAd();
        // } else {//未展开则搜索名称
        //     parame ={sysid:null, name:name};
        // }
        myParame.setParame(parame);
    }

    /**
     * 校验外部系统地址
     * @param form
     * @param ids
     * @returns {boolean}
     */
    checkUrl(form, ids) {
        if (ids != null) {
            const idArr = ids.split(",");
            for (let i = 0; i < idArr.length; i++) {
                const id = idArr[i];
                let value = "";
                if ("serverUrl" === id) {
                    value = form.getFormDatas().serverUrl.value;
                } else if ("goPage" === id) {
                    value = form.getFormDatas().goPage.value;
                } else {
                    continue;
                }
                if (0 !== value.toLowerCase().indexOf("http")) {
                    Modal.warning({
                        title: getLabel(15172, "系统提示"),
                        content: getLabel(386567, "外部地址，请在地址前加上http://或https://"),
                        onOk() {
                            form.showErrors();
                        },
                        onCancel() {
                            form.showErrors();
                        }
                    });
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 保存数据前的操作 主要是必填验证等
     */
    fnSaverCreateDatas = () => {
        const {myCreateForm, myParame} = this.props;
        const {alldatas, hiddenid, tabledata, updateLoading, ispublics, nodedatas, dataprocessing, doValidate,isorder} = myCreateForm;
        const {form} = alldatas;
        const {selectedKey,toptab} = myParame;//获取当前打开的是哪一个table
        let params = form.getFormParams();
        params['tabledatas'] = JSON.stringify(tabledata);//转为json字符串
        params['hiddenid'] = hiddenid;
        params["tabKey"] = selectedKey;

        let callback = this.fncanceldialog;
        if(toptab && toptab[selectedKey] && toptab[selectedKey].groupid) {
            params["tabGroupid"] = toptab[selectedKey].groupid;
            if(toptab[selectedKey].groupid == Static.TAB_QYS_INTEGRATIONCONFIG) {
                callback = myCreateForm.setFormDatas;//.bind(myParame.getCreateUrl(), parame);
            }
        }
        let canSave = true;

        if(selectedKey == 1) {//契约锁集成特殊处理--服务类型
            params['serverType'] =ispublics?"0":"1";
            params["nodedatas"] = JSON.stringify(nodedatas);
            params =  dataprocessing(params);
            params["signOrder"] = isorder ? 1 : 0;
            canSave = doValidate();//主要验证表格中的必填项
        }

        //必填验证
        form.validateForm().then(f => {
            if (f.isValid && canSave) {// 验证通过,  执行保存方法
                if (0 == selectedKey) { // 契约锁服务配置，校验API服务地址和契约锁系统地址是否有效
                    canSave = this.checkUrl(form, "serverUrl,goPage");
                }
                if (canSave) {
                    updateLoading(true);
                    let dtIdList = this.props.myCreateForm.dtIdList.join(",");
                    params = {...params,dtids:dtIdList};
                    Public.getInterfaceSeted(params).then(result => {
                        updateLoading(false);
                        if (result.status == 1) {
                            Modal.success({
                                title: getLabel(15172, "系统提示"),
                                content: getLabel(18758, "保存成功!"),
                                onOk() {
                                    if (params && params.tabGroupid && params.tabGroupid == Static.TAB_QYS_INTEGRATIONCONFIG) {
                                        callback && callback(myParame.getCreateUrl(), {
                                            formtype: "getEditForm",
                                            id: result.id
                                        });
                                    } else {
                                        callback && callback();
                                    }
                                },
                            });
                        } else if (result.status == 10) {//保存成功，但是需要修改流程模板插入契约锁代码
                            Modal.confirm({
                                title: getLabel(15172, "系统提示"),
                                content: getLabel(500964, "此流程自定义页面已被占用，需要手动在HTML模板中插入代码块，是否现在设置？"),
                                okText: getLabel(163, "是"),
                                cancelText: getLabel(30587, "否"),
                                onOk() {
                                    Public.goToPathSetting(params.workflowid);
                                },
                            })
                        } else {
                            Modal.error({
                                title: getLabel(15172, "系统提示"),
                                content: result.msg || getLabel(84544, "保存失败!"),
                            })
                        }
                    })
                }
            } else {
                Modal.warning({
                    title: getLabel(15172, "系统提示"),
                    content: getLabel(388248, "存在必填项未填写！"),
                    onOk() {
                        f.showErrors();
                    },
                    onCancel() {
                        f.showErrors();
                    }
                });
            }
        });
    }

    /**
     * 通过btn的key获取对应的onclick方法
     * @param key
     * @returns {*}
     */
    fnGetFunction =(key)=> {
        if(key == 1){
            return this.fnSearch();
        }else if(key == 2) {
            return this.fnCreateParam("getCreateForm", null);
        } else if(key == 3) {
            return this.fndelete();
        } else if(key == 4) {
            return this.fnColSetVisible();
        } else if(key == 5) {
            const {myParame} = this.props;
            return myParame.setVisiblecollect()
        } else if(key =="3.1") {//一键初始化
            const {myParame} = this.props;
            return myParame.setShowInitialization(true)
        }else if(key == "4.1"){//契约锁相关配置执行
            let {immediatelyRun} = this.props.myParame;
            immediatelyRun();
        }
    }

    /**
     * 获得右键公共菜单
     */
    fnGetRightBtn = () => {
        const {loading,} = this.state;
        const {myParame} = this.props;
        const {selectedKey, toptab} = myParame;
        let btns = [];
        if( !selectedKey || toptab.length < 1) {
            return btns;
        }
        if (toptab[selectedKey] && toptab[selectedKey].btns) {
            toptab[selectedKey].btns.map((item, index) => {
                btns.push({
                    key: item.key,
                    disabled: loading,
                    icon:<i className={item.icon}/>,
                    content: item.content,
                    onClick: () => this.fnGetFunction(item.key),
                })
            })
        }
        return btns;
    }

    /**
     * 主页顶部公共菜单
     * @returns {*[]}
     */
    fnGetTopBtns = () => {
        const {myParame} = this.props;
        const {selectedKey, toptab} = myParame;
        let btns = [];
        if( !selectedKey || toptab.length < 1) {
            return btns;
        }
        if (toptab[selectedKey] && toptab[selectedKey].btns) {
            toptab[selectedKey].btns.map((item, index) => {
                item.isShowTop && btns.push(<Button type={btns.length == 0?"primary":"glost"} onClick={() => this.fnGetFunction(item.key)}>{item.content}</Button> )
            })
        }
        return btns;
    }

    /**
     * 弹框底部公共按钮
     * @param clickSave 保存方法
     * @param clickClear 取消的方法
     * @loading 数据是否还在加载中
     */
    fnGetBottmoBtns = (clickSave, clickClear  ,loading=true) => {
        return [
            (<Button type="primary"  disabled={loading} onClick={clickSave.bind()}>{getLabel(86, "保存")}</Button>),
            (<Button type="ghost" onClick={clickClear.bind()}>{getLabel(201, "取消")}</Button>)
        ]
    }

    /**
     * 添加底部菜单
     */
    fnAddBottmBtn = (buttons, loading = false) => {
        const {myCreateForm} = this.props;
        const {alldatas, addbtns} = myCreateForm
        const {formtype = "getCreateForm"} = alldatas;
        if (formtype == "getEditForm") {
            buttons && addbtns && addbtns.map(item => {
                if (item.isbottombtn) buttons.splice(item.index, 0, (
                    <Button type="glost" disabled={loading} onClick={item.click.bind(true)}>{item.name}</Button>))
            })
        }
    }
    /**
     * 保存的过度方法，便于他人理解
     */
    excessiveSaveInterfaceSetting = () => {
        const {myCusIntSet, myCreateForm} = this.props;
        const {tabledata, doSaveInterfaceSetting} = myCusIntSet;
        const {alldatas, setShowInterface} = myCreateForm;
        const {workflowid} = alldatas;//用于判断id是否存在，存在才开始保存
        doSaveInterfaceSetting({
            tabledatas: JSON.stringify(tabledata),
            workflowid: workflowid
        }, setShowInterface)
    }

    componentWillMount(){
        window.QYS = {fnEditForm:(id) => {this.fnEditForm(id);}}
    }


    render() {
        const {title, visibleCustomized,  isRight = true} = this.state;
        const {myParame, myDelete, myTopcol, myCreateForm} = this.props;
        let {running,urlend, parame, showkey, visiblecollect, visibleshowcreate, visibledialog, createurl, paramsform, selectedKey, visibledInitialization = false, hasRight = false} = myParame;
		if(!hasRight) {//权限判断
            return <QYS_Right/>
        }
        const {islayout = false, myheight} = myTopcol;
        let {deletevisible} = myDelete;
        const {isShowInterface, setShowInterface, customtitle, loading} = myCreateForm;

        //新建编辑的弹框底部按钮
        let diabottombtns = this.fnGetBottmoBtns(this.fnSaverCreateDatas, this.fncanceldialog, loading);
        selectedKey == 1 && this.fnAddBottmBtn(diabottombtns, loading)

        // 自定义接口设置的底部按钮
        let interfacebtns = this.fnGetBottmoBtns(() => {this.excessiveSaveInterfaceSetting();},  () => {setShowInterface()}, false);

        // 主页的右键菜单按钮
        let dropmenubtn = this.fnGetRightBtn();
        //主页的顶部按钮
        let topbtns = this.fnGetTopBtns();

        //正真的数据展示窗口
        let getreturn = <div>
            <WeaTop
                title={<span style={{color: '#484a4d'}}>{title}</span>}//标题
                icon={<i className='icon-coms-integration-o'/>}//图标
                iconBgcolor='#1a57a0'//图标背景色
                buttons={topbtns}//顶部按钮
                showDropIcon={true}//显示下拉选
                dropMenuDatas={dropmenubtn}//下拉菜单
            />
            <WeaDialog
                visible={visibledialog}
                onCancel={() => this.fncanceldialog()}
                title={myParame.getTitleMsg()}
                style={{width: 1000, height: 600}}
                buttons={diabottombtns}
                maskClosable={false}
                /*hasScroll*/>
                <IntegrationForm//新建表单
                    fnSaverCreateDatas={this.fnSaverCreateDatas}
                    fncanceldialog={this.fncanceldialog}
                    selectedKey={selectedKey}
                    toptab={myParame.toptab}
                    checkUrl={this.checkUrl}
                />
                <WeaDialog
                    visible={isShowInterface}
                    onCancel={() => setShowInterface(false)}
                    title={customtitle}
                    style={{width: 1200, height: 590}}
                    buttons={interfacebtns}
                    maskClosable={false}
                    /*hasScroll*/>
                    <CustomInterfaceSetting></CustomInterfaceSetting>
                </WeaDialog>
            </WeaDialog>
            {visibledInitialization && <Initialization title={getLabel(500940, "一键初始化")}/>}
            <WeaCollect  //收藏
                visible={visiblecollect}
                favname={title}
                favouritetype={2}
                importantlevel={1}
                onClose={() => myParame.setVisiblecollect()}
            />

            <TopColumn
                islayout={islayout}
                myheight={myheight}/>
            <MainDataList//表单数据
                key={0}
                fnGoDelete={this.fnGoDelete}//删除
                fnEditForm={this.fnEditForm}//编辑
            />
        </div>;
        if (isRight) {
            return (
                <div style={{height: "100%"}}>
                    <WeaRightMenu datas={dropmenubtn}>
                        {getreturn}
                    </WeaRightMenu>
                    {   //判断是否在执行中
                        running ? <div className={"running"}>
                                    <Spin className={"spin"}/>
                                   </div> : false
                    }
                </div>
            );
        } else {
            return (
                <div>
                    {getreturn}
                    {   //判断是否在执行中
                        running ? <div className={"running"}>
                            <Spin className={"spin"}/>
                        </div> : false
                    }
                </div>
            );
        }
    }
}

export default Mainpage
